<template>
  <div>
    <ul>
      <li v-for="item in 50" :key="item" class="li-item" :id="item === 20 ? 'target' : ''">
        {{ item === 20 ? 'target - ' + item : item }}
      </li>
    </ul>
    <el-button @click="toBack">go back</el-button>

    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="Password" prop="pass">
        <el-input v-model="ruleForm.pass" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="Confirm" prop="checkPass">
        <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="Age" prop="age">
        <el-input v-model.number="ruleForm.age"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">Submit</el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const toBack = () => {
  router.push({ name: 'home' })
}

const ruleForm = reactive({
  pass: '',
  checkPass: '',
  age: ''
})

const checkAge = (rule, value, callback) => {
  if (!value) {
    callback(new Error('Please input the age'))
    return
  }
  setTimeout(() => {
    if (!Number.isInteger(value)) {
      callback(new Error('Please input digits'))
    } else if (value < 18) {
      callback(new Error('Age must be greater than 18'))
    } else {
      callback()
    }
  }, 1000)
}

const validatePass = (rule, value, callback) => {
  console.log(rule, value, callback)
}
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please input the password again'))
  } else if (value !== ruleForm.pass) {
    callback(new Error("Two inputs don't match!"))
  } else {
    callback()
  }
}

const rules = reactive({
  pass: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass2, trigger: 'blur' }],
  age: [{ validator: checkAge, trigger: 'blur' }]
})

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!')
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style lang="scss" scoped>
.li-item {
  line-height: 30px;
  margin: 5px 0;
  background-color: lightblue;
}
</style>
